%% 2Choice Task
rv = schedule.response_vals;

rcidx = regexp(schedule.readparams,'response_code');
rcidx = findincell(rcidx) + 1;
ttidx = regexp(schedule.readparams,'trial_type');
ttidx = findincell(ttidx) + 1;

vals   = rv(:,rcidx); vals(isnan(vals))     = [];
trials = rv(:,ttidx); trials(isnan(trials)) = [];

% AM State = 2
AMhits = bitget(vals,6) & bitget(vals,13);
AMmiss = bitget(vals,5) & bitget(vals,13);

% Quiet State = 1
Qhits  = bitget(vals,6) & bitget(vals,12);
Qmiss  = bitget(vals,5) & bitget(vals,12);

% Tone State = 0
Thits  = bitget(vals,6) & bitget(vals,11);
Tmiss  = bitget(vals,5) & bitget(vals,11);

% totals
r = sum([AMhits AMmiss Qhits Qmiss Thits Tmiss]);
AMhr = r(1)/sum(r([1 2]))*100;
Qhr  = r(3)/sum(r([3 4]))*100;
Thr  = r(5)/sum(r([5 6]))*100;
Ohr  = mean([AMhr Qhr Thr]);

% print results to command window
fprintf('\n%s\n',schedule.schedule);
fprintf('\tHit\t\tMiss\tHR\n')
fprintf('AM\t%d\t\t%d\t\t%3.1f%%\n',r([1 2]),AMhr)
fprintf('Q\t%d\t\t%d\t\t%3.1f%%\n', r([3 4]),Qhr)
fprintf('T\t%d\t\t%d\t\t%3.1f%%\n', r([5 6]),Thr)
fprintf('#trials = %3.0f\t\t%3.1f%%\n\n',sum(r),Ohr);

% plot by trials
figure('windowstyle','docked');
clf
subplot(211)
hold on
% plot(find(trials==2),AMhits(trials==2),'>b')
% plot(find(trials==1),Qhits(trials==1), '>r')
% plot(find(trials==0),Thits(trials==0), '<g')
set(gca,'ytick',[0 25 50 75 100]);
grid on
plot(cumsum(AMhits)./cumsum(trials==2)*100,'.b');
plot(cumsum(Qhits) ./cumsum(trials==1)*100,'.r');
plot(cumsum(Thits) ./cumsum(trials==0)*100,'.g');
xlim([0 length(trials)]);
ylim([-10 110]);
box on
title('Running Hit Rate');
xlabel('Trial number');
ylabel('Hit rate');
hold off
legend('AM','Quiet','Tone','location','best')

subplot(212)
bar([AMhr Qhr Thr Ohr]);
set(gca,'ytick',[0 25 50 75 100]);
grid on
box on
set(gca,'xticklabel',{'AM','Quiet','Tone','Overall'},'ylim',[0 100]);
ylabel('Hit Rate');

